import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";

interface PermissionRouteProps {
  children: React.ReactNode;
  roles?: string[];
}

const PermissionRoute: React.FC<PermissionRouteProps> = ({ children, roles }) => {
  const location = useLocation();
  // 从 redux 获取当前用户角色，未登录默认为空
  const userRole = useSelector((state: any) => state.user.profile?.role || "");

  if (!userRole) {
    // 未登录，跳转登录页
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  if (roles && !roles.includes(userRole)) {
    // 没有权限，跳转403
    return <Navigate to="/error/403" replace />;
  }

  return <>{children}</>;
};

export default PermissionRoute; 